package com.ayf.payment.game.api.channel.qiyi;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.bean.BaseResData;
import com.ayf.payment.game.api.channel.BaseHandler;
import com.ayf.payment.game.api.channel.qiyi.util.QiYiSignUtil;
import com.ayf.payment.game.api.dto.platform.SubstitutePayConfigDTO;
import com.ayf.payment.game.api.dto.platform.pay.WanXiangPayConfigParamVO;
import com.ayf.payment.game.api.exception.NullSetException;
import com.ayf.payment.game.api.httpclient.HttpUtils;
import com.ayf.payment.game.api.service.platform.SubstitutePayConfigService;
import com.ayf.payment.game.api.type.MerchantPayOrderStatusEnum;
import com.ayf.payment.game.api.utils.BigDecimalUtil;
import com.ayf.payment.game.api.utils.DateUtils;
import com.ayf.payment.game.api.utils.RandomStrUtils;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;
import java.util.TreeMap;

@Component
public class QiYiPayHander implements BaseHandler {

    @Autowired
    private SubstitutePayConfigService substitutePayConfigService;

    @Override
    public JSONObject orderCreate(JSONObject inputParam) {
        JSONObject resJson = new JSONObject();
        String merchantOrderNo = inputParam.getString("merchant_order_no");
        resJson.put("merchantOrderNo", merchantOrderNo);
        resJson.put("status", MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus());

        String methodDesc = "奇异代付下单";
        String traceId = inputParam.getString("traceId");
        Integer substitutePayConfigId = inputParam.getInteger("substitutePayConfigId");
        SubstitutePayConfigDTO substitutePayConfigDTO = substitutePayConfigService.getSubstitutePayConfigById(substitutePayConfigId);
        WanXiangPayConfigParamVO wanXiangPayConfigParamVO = substitutePayConfigDTO.getWanXiangPayConfigParamVO();

        BaseResData baseResData = orderCreate(traceId,methodDesc,wanXiangPayConfigParamVO,inputParam);
        if (baseResData.isProcessing()){
            resJson.put("status", MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus());
        } else {
            if (baseResData.isSuccess()){
                JSONObject jsonResult = JSONObject.parseObject(baseResData.getData());
                String status = jsonResult.getString("status");
                String message = jsonResult.getString("message");
                if ("1".equals(status)){ // 提交成功
                    resJson.put("status", MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus());
                } else {
                    resJson.put("status", MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
                    resJson.put("failReason",message);
                    LogPortal.error("{} {}失败，请求接口成功，接口返回错误码:{} 错误描述:{}",traceId,methodDesc,status,message);
                }
            } else {
                resJson.put("status", MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
                resJson.put("failReason",baseResData.getRespMsg());
                LogPortal.error("{} {}失败，请求接口失败，返回错误码:{} 错误描述:{}",traceId,methodDesc,baseResData.getRespCode(),baseResData.getRespMsg());
            }
        }
        LogPortal.info("{} {} 响应报文[{}]", traceId,methodDesc,resJson.toJSONString());
        return resJson;
    }

    @Override
    public JSONObject orderQuery(JSONObject inputParam) {
        JSONObject resJson = new JSONObject();
        String merchantOrderNo = inputParam.getString("merchant_order_no");
        resJson.put("merchantOrderNo", merchantOrderNo);
        resJson.put("status", MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus());

        String traceId = inputParam.getString("traceId");
        String methodDesc = "奇异代付订单查询";

        Integer substitutePayConfigId = inputParam.getInteger("substitutePayConfigId");
        SubstitutePayConfigDTO substitutePayConfigDTO = substitutePayConfigService.getSubstitutePayConfigById(substitutePayConfigId);
        WanXiangPayConfigParamVO wanXiangPayConfigParamVO = substitutePayConfigDTO.getWanXiangPayConfigParamVO();
        BaseResData baseResData = orderQuery(traceId,methodDesc,wanXiangPayConfigParamVO,merchantOrderNo);
        if (baseResData.isProcessing()){
            LogPortal.error("{} 订单号[{}] {}失败 请求接口成功，接口响应超时",traceId,methodDesc,merchantOrderNo);
            return resJson;
        }
        if (baseResData.isSuccess()){
            JSONObject jsonResult = JSONObject.parseObject(baseResData.getData());
            String status = jsonResult.getString("status");
            String message = jsonResult.getString("message");
            if ("1".equals(status)){
                // 订单状态，1-代付成功，2-管理员驳回，3-失败，0-处理中
                String order_status = jsonResult.getString("order_status");
                if (StringUtils.isEmpty(order_status) || "0".equals(order_status)){
                    return resJson;
                }
                if ("1".equals(order_status)){
                    resJson.put("status", MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
                } else if ("2".equals(status)||"3".equals(status)){
                    resJson.put("status", MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
                    if ("2".equals(status)){
                        resJson.put("failReason","接口方：管理员驳回");
                    }
                }
            } else {
                LogPortal.error("{} {}失败，请求接口成功，渠道返回错误码:{} 错误描述:{}",traceId,methodDesc,status,message);
            }
        } else {
            LogPortal.error("{} {}失败 请求接口失败，错误码:{} 错误描述:{}",traceId,methodDesc,baseResData.getRespCode(),baseResData.getRespMsg());
        }
        LogPortal.info("{} 奇异代付订单查询 订单号:{} 响应报文[{}]", traceId,merchantOrderNo,resJson.toJSONString());
        return resJson;
    }

    @Override
    public JSONObject balanceQuery(JSONObject inputParam) {
        JSONObject resJson = new JSONObject();
        String traceId = inputParam.getString("traceId");
        String bankName = inputParam.getString("bankName");
        String bankType = getBankType(traceId, bankName);
        if (StringUtils.isEmpty(bankType)) {
            resJson.put("status", "2");
            return resJson;
        }
        resJson.put("status", "1");
        resJson.put("balance", "10000000.00");
        return resJson;
    }

    private BaseResData orderCreate(String traceId, String methodName,WanXiangPayConfigParamVO wanXiangPayConfigParamVO,JSONObject inputParam){
        String merchantOrderNo = inputParam.getString("merchant_order_no");
        String AuthorizationURL = wanXiangPayConfigParamVO.getWebsite();
        String notifyUrl = wanXiangPayConfigParamVO.getNotifyurl();
        if (StringUtils.isEmpty(AuthorizationURL)){
            LogPortal.error("{} {} 失败，通道代付地址不能为空，订单号:{}",traceId,methodName,merchantOrderNo);
            throw new NullSetException(traceId + "代付订单下单失败，请稍后重试！");
        }
        if (StringUtils.isEmpty(notifyUrl)){
            LogPortal.error("{} {} 失败，代付异步通知地址不能为空，订单号:{}",traceId,methodName,merchantOrderNo);
            throw new NullSetException(traceId + "代付异步通知地址不能为空，请稍后重试！");
        }
        if (!AuthorizationURL.endsWith("/")){
            AuthorizationURL=AuthorizationURL.concat("/");
        }
        if (!notifyUrl.endsWith("/")){
            notifyUrl=notifyUrl.concat("/");
        }
        AuthorizationURL=AuthorizationURL.concat("main/submitpayee");

        BigDecimal amount = inputParam.getBigDecimal("amount");
        String username = inputParam.getString("account_name");
        String bankName = inputParam.getString("bank_name");
        String bankCode = getBankType(traceId, bankName);
        String bankno = inputParam.getString("account_no");

        Map<String,String> reqParam = new TreeMap<>();
        reqParam.put("user_id",wanXiangPayConfigParamVO.getParter());
        reqParam.put("order_id",merchantOrderNo);
        reqParam.put("total_fee",String.valueOf(BigDecimalUtil.yuanToFen(amount)));// 代付金额,单位分
        reqParam.put("acc_type","1");//1-对私
        reqParam.put("acc_name",username);
        reqParam.put("bank_acc",bankno);
        reqParam.put("bank_code",bankCode);
        reqParam.put("charset","UTF-8");
        reqParam.put("order_date",DateUtils.dateToString(DateUtils.getNowDate(),DateUtils.formatPattern_full_01));
        reqParam.put("notify_url",notifyUrl.concat("gameapip/v/qiyi/pay/paynotify"));
        reqParam.put("attach","");

        String sign = QiYiSignUtil.getSign(traceId,methodName,reqParam,wanXiangPayConfigParamVO.getKey());
        reqParam.put("sign",sign);
        BaseResData result = HttpUtils.sendPostForm(traceId,methodName,AuthorizationURL,reqParam);
        return result;
    }


    private BaseResData orderQuery(String traceId, String methodName,WanXiangPayConfigParamVO wanXiangPayConfigParamVO,String merchantOrderNo){
        String AuthorizationURL = wanXiangPayConfigParamVO.getWebsite();
        if (StringUtils.isEmpty(AuthorizationURL)){
            LogPortal.error("{} 失败，通道代付订单查询地址不能为空，订单号:{}",traceId,merchantOrderNo);
            throw new NullSetException(traceId + "代付订单查询失败，请稍后重试！");
        }
        if (!AuthorizationURL.endsWith("/")){
            AuthorizationURL=AuthorizationURL.concat("/");
        }
        AuthorizationURL=AuthorizationURL.concat("main/querypayee");

        Map<String,String> reqParam = new TreeMap<>();
        reqParam.put("user_id",wanXiangPayConfigParamVO.getParter());
        reqParam.put("order_id",merchantOrderNo);
        reqParam.put("charset","UTF-8");

        String sign =QiYiSignUtil.getSign(traceId,methodName,reqParam,wanXiangPayConfigParamVO.getKey());
        reqParam.put("sign",sign);
        BaseResData result = HttpUtils.sendPostForm(traceId,methodName,AuthorizationURL,reqParam);
        return result;
    }


    private String getBankType(String traceId, String bankName) {
        if (bankName.contains("农业银行")) {
            return "ABC";
        } else if (bankName.contains("中国银行")) {
            return "BOC";
        } else if (bankName.contains("建设银行")) {
            return "CCB";
        } else if (bankName.contains("交通银行")) {
            return "COMM";
        } else if (bankName.contains("招商银行")) {
            return "CMB";
        } else if (bankName.contains("广东发展银行")||bankName.contains("广发银行")) {
            return "GDB";
        } else if (bankName.contains("中信银行")) {
            return "CITIC";
        } else if (bankName.contains("民生银行")) {
            return "CMBC";
        } else if (bankName.contains("光大银行")) {
            return "CEB";
        } else if (bankName.contains("平安银行")) {
            return "PINGAN";
        } else if (bankName.contains("浦发银行")||bankName.contains("浦东发展")) {
            return "SPDB";
        } else if (bankName.contains("邮政储蓄")) {
            return "PSBC";
        } else if (bankName.contains("华夏银行")) {
            return "HXB";
        } else if (bankName.contains("兴业银行")) {
            return "CIB";
        }else if (bankName.contains("工商银行")) {
            return "ICBC";
        }else if (bankName.contains("深圳发展银行")) {
            return "SDB";
        } else {
            LogPortal.error("[{}]奇异代付银行类别错误[{}]", traceId, bankName);
            return null;
        }
    }

    private static void testOrderCreate(){
        String traceId =  SnowFlakeUtils.getTraceId();
        JSONObject inputParam = new JSONObject();
        inputParam.put("merchant_order_no","Y".concat(RandomStrUtils.createRandom(true,8)));
        inputParam.put("amount","1");
        inputParam.put("account_name","张三");
        inputParam.put("bank_name","招商银行");
        inputParam.put("account_no","6225880132496432");
        WanXiangPayConfigParamVO wanXiangPayConfigParamVO = getTestWanXiangPayConfigParamVO();
        QiYiPayHander zhuoFuTongPayHandler = new QiYiPayHander();
        zhuoFuTongPayHandler.orderCreate(traceId,"奇异代付下单",wanXiangPayConfigParamVO,inputParam);
    }


    private static void testOrderQuery(){
        String traceId =  SnowFlakeUtils.getTraceId();
        String merchantOrderNO = "Y2021030194487019";
        WanXiangPayConfigParamVO wanXiangPayConfigParamVO = getTestWanXiangPayConfigParamVO();
        QiYiPayHander zhuoFuTongPayHandler = new QiYiPayHander();
        zhuoFuTongPayHandler.orderQuery(traceId,"奇异代付订单查询",wanXiangPayConfigParamVO,merchantOrderNO);
    }



    /**
     * 构造测试请求通道商户参数
     * @return
     */
    private static WanXiangPayConfigParamVO getTestWanXiangPayConfigParamVO(){
        WanXiangPayConfigParamVO wanXiangPayConfigParamVO = new WanXiangPayConfigParamVO();
        wanXiangPayConfigParamVO.setWebsite("https://ipay.qyiol.com");
        wanXiangPayConfigParamVO.setParter("2220");
        wanXiangPayConfigParamVO.setKey("c920c3b20474d27c852894c542fa9b7d");
        wanXiangPayConfigParamVO.setNotifyurl("http://uatxy.xyouplay.com");
        return wanXiangPayConfigParamVO;
    }

    public static void main(String[] args) {
//        testOrderCreate();
        testOrderQuery();
    }
}
